// 仪表板视图组件
import React, { useState, useEffect } from 'react';
import { invoke } from '@tauri-apps/api/core';

interface DashboardViewProps {
  className?: string;
}

interface ProjectStats {
  totalFiles: number;
  totalLines: number;
  languages: Record<string, number>;
  lastAnalyzed: string;
}

interface RecentActivity {
  id: string;
  type: 'file_opened' | 'file_saved' | 'analysis_completed';
  description: string;
  timestamp: string;
}

export const DashboardView: React.FC<DashboardViewProps> = ({ className }) => {
  const [projectStats, setProjectStats] = useState<ProjectStats | null>(null);
  const [recentActivity, setRecentActivity] = useState<RecentActivity[]>([]);
  const [isLoading, setIsLoading] = useState(true);

  // 加载仪表板数据
  const loadDashboardData = async () => {
    setIsLoading(true);
    try {
      // 获取项目统计信息
      const statsResponse = await invoke('get_project_stats') as any;
      if (statsResponse.success) {
        setProjectStats(statsResponse.data);
      }

      // 获取最近活动
      const activityResponse = await invoke('get_recent_activity') as any;
      if (activityResponse.success) {
        setRecentActivity(activityResponse.data);
      }
    } catch (error) {
      console.error('Failed to load dashboard data:', error);
      // 设置模拟数据
      setProjectStats({
        totalFiles: 156,
        totalLines: 12543,
        languages: {
          'TypeScript': 45,
          'Rust': 30,
          'JavaScript': 15,
          'CSS': 10
        },
        lastAnalyzed: new Date().toISOString()
      });

      setRecentActivity([
        {
          id: '1',
          type: 'file_opened',
          description: '打开文件 App.tsx',
          timestamp: new Date(Date.now() - 5 * 60 * 1000).toISOString()
        },
        {
          id: '2',
          type: 'file_saved',
          description: '保存文件 router.ts',
          timestamp: new Date(Date.now() - 10 * 60 * 1000).toISOString()
        },
        {
          id: '3',
          type: 'analysis_completed',
          description: '代码分析完成',
          timestamp: new Date(Date.now() - 30 * 60 * 1000).toISOString()
        }
      ]);
    } finally {
      setIsLoading(false);
    }
  };

  useEffect(() => {
    loadDashboardData();
  }, []);

  const formatTimestamp = (timestamp: string) => {
    const date = new Date(timestamp);
    const now = new Date();
    const diff = now.getTime() - date.getTime();
    
    if (diff < 60000) return '刚刚';
    if (diff < 3600000) return `${Math.floor(diff / 60000)} 分钟前`;
    if (diff < 86400000) return `${Math.floor(diff / 3600000)} 小时前`;
    return date.toLocaleDateString();
  };

  const getActivityIcon = (type: RecentActivity['type']) => {
    switch (type) {
      case 'file_opened': return '📂';
      case 'file_saved': return '💾';
      case 'analysis_completed': return '🔍';
      default: return '📄';
    }
  };

  if (isLoading) {
    return (
      <div className={`flex-1 flex items-center justify-center ${className || ''}`}>
        <div className="text-center">
          <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-blue-500 mx-auto mb-4"></div>
          <p className="text-gray-600 dark:text-gray-400">加载仪表板数据...</p>
        </div>
      </div>
    );
  }

  return (
    <div className={`flex-1 p-6 overflow-auto ${className || ''}`}>
      <div className="max-w-7xl mx-auto">
        {/* 页面标题 */}
        <div className="mb-8">
          <h1 className="text-3xl font-bold text-gray-900 dark:text-white mb-2">
            项目仪表板
          </h1>
          <p className="text-gray-600 dark:text-gray-400">
            查看项目统计信息和最近活动
          </p>
        </div>

        {/* 统计卡片 */}
        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6 mb-8">
          <div className="bg-white dark:bg-gray-800 rounded-lg shadow p-6">
            <div className="flex items-center">
              <div className="p-2 bg-blue-100 dark:bg-blue-900 rounded-lg">
                <span className="text-2xl">📁</span>
              </div>
              <div className="ml-4">
                <p className="text-sm font-medium text-gray-600 dark:text-gray-400">
                  总文件数
                </p>
                <p className="text-2xl font-bold text-gray-900 dark:text-white">
                  {projectStats?.totalFiles || 0}
                </p>
              </div>
            </div>
          </div>

          <div className="bg-white dark:bg-gray-800 rounded-lg shadow p-6">
            <div className="flex items-center">
              <div className="p-2 bg-green-100 dark:bg-green-900 rounded-lg">
                <span className="text-2xl">📝</span>
              </div>
              <div className="ml-4">
                <p className="text-sm font-medium text-gray-600 dark:text-gray-400">
                  总代码行数
                </p>
                <p className="text-2xl font-bold text-gray-900 dark:text-white">
                  {projectStats?.totalLines?.toLocaleString() || 0}
                </p>
              </div>
            </div>
          </div>

          <div className="bg-white dark:bg-gray-800 rounded-lg shadow p-6">
            <div className="flex items-center">
              <div className="p-2 bg-purple-100 dark:bg-purple-900 rounded-lg">
                <span className="text-2xl">🔤</span>
              </div>
              <div className="ml-4">
                <p className="text-sm font-medium text-gray-600 dark:text-gray-400">
                  编程语言
                </p>
                <p className="text-2xl font-bold text-gray-900 dark:text-white">
                  {Object.keys(projectStats?.languages || {}).length}
                </p>
              </div>
            </div>
          </div>

          <div className="bg-white dark:bg-gray-800 rounded-lg shadow p-6">
            <div className="flex items-center">
              <div className="p-2 bg-orange-100 dark:bg-orange-900 rounded-lg">
                <span className="text-2xl">⏰</span>
              </div>
              <div className="ml-4">
                <p className="text-sm font-medium text-gray-600 dark:text-gray-400">
                  最后分析
                </p>
                <p className="text-sm font-bold text-gray-900 dark:text-white">
                  {projectStats?.lastAnalyzed ? formatTimestamp(projectStats.lastAnalyzed) : '未知'}
                </p>
              </div>
            </div>
          </div>
        </div>

        <div className="grid grid-cols-1 lg:grid-cols-2 gap-8">
          {/* 语言分布 */}
          <div className="bg-white dark:bg-gray-800 rounded-lg shadow p-6">
            <h2 className="text-xl font-bold text-gray-900 dark:text-white mb-4">
              语言分布
            </h2>
            <div className="space-y-3">
              {Object.entries(projectStats?.languages || {}).map(([language, percentage]) => (
                <div key={language} className="flex items-center">
                  <div className="w-20 text-sm text-gray-600 dark:text-gray-400">
                    {language}
                  </div>
                  <div className="flex-1 mx-3">
                    <div className="bg-gray-200 dark:bg-gray-700 rounded-full h-2">
                      <div
                        className="bg-blue-500 h-2 rounded-full"
                        style={{ width: `${percentage}%` }}
                      ></div>
                    </div>
                  </div>
                  <div className="w-12 text-sm text-gray-900 dark:text-white text-right">
                    {percentage}%
                  </div>
                </div>
              ))}
            </div>
          </div>

          {/* 最近活动 */}
          <div className="bg-white dark:bg-gray-800 rounded-lg shadow p-6">
            <h2 className="text-xl font-bold text-gray-900 dark:text-white mb-4">
              最近活动
            </h2>
            <div className="space-y-3">
              {recentActivity.map((activity) => (
                <div key={activity.id} className="flex items-center p-3 bg-gray-50 dark:bg-gray-700 rounded-lg">
                  <div className="text-2xl mr-3">
                    {getActivityIcon(activity.type)}
                  </div>
                  <div className="flex-1">
                    <p className="text-sm font-medium text-gray-900 dark:text-white">
                      {activity.description}
                    </p>
                    <p className="text-xs text-gray-500 dark:text-gray-400">
                      {formatTimestamp(activity.timestamp)}
                    </p>
                  </div>
                </div>
              ))}
            </div>
          </div>
        </div>
      </div>
    </div>
  );
};
